package ude.univ.esiag.gon.uchiha.reader;

import ude.univ.esiag.gon.uchiha.core.DCSClient;
import ude.univ.esiag.gon.uchiha.operation.Operation;
import ude.univ.esiag.gon.uchiha.register.MulticasterClient;
import ude.univ.esiag.gon.uchiha.subscriber.DataReactor;
import ude.univ.esiag.gon.uchiha.subscriber.Subscriber;
import ude.univ.esiag.gon.uchiha.subscriber.impl.SubscriberImpl;

public class DataReaderClient implements DataReaderListener{
	private SubscriberImpl subscriber;
	private String topicName;
	private DataReactor dataReactor;
	private static DataReaderClient instance;
	public DataReaderClient(String topicName) {
		this.dataReactor = DataReactor.newInstance();
		subscriber = dataReactor.addListener(this);
		this.topicName = topicName;
	}
	public static DataReaderClient getInstance(String topicName){
		if(instance == null){
			instance = new DataReaderClient(topicName);
		}
		instance.topicName = topicName;
		return instance;
	}
	public SubscriberImpl getSubscriber() {
		return subscriber;
	}
	public DataReactor getDataReactor() {
		return dataReactor;
	}
	public void signal(final String topicName) {
		if(!topicName.equals(this.topicName))
			return;
		new Thread(new Runnable() {
			public void run() {
				Operation op = subscriber.read(topicName);
				if(op == null)
					return;
				traite(op);
			}
		}).start();
	}
	synchronized private void traite(Operation op){
		DCSClient client = DCSClient.getInstance();
		if(op.getTarget() == Operation.TOPIC){
			if(op.getType() == Operation.IOR){
				if(!client.isWritable()){
					Subscriber subscriber = MulticasterClient.getInstance().ior_to_subscriber((String)op.getData().getObj());
					client.setDataWriter(subscriber);
				}
			}
			else if(op.getType() == Operation.ERROR){
				System.out.println("Error : " + op.getData().getObj());
			}
		}
		if(op.getTarget() == Operation.CACHE){
			if(op.getType() == Operation.READ){
				client.setData(op.getData().getObj());
			}
		}
	}
}
